package com.hmall.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Mr.Wen
 * @Version 1.0
 * 获取网关中携带的请求头中的用户信息（是否是登录用户）
 */
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userinfo = request.getHeader("user-info");
//        有用户信息就存入ThreadLocal
        if (StrUtil.isNotBlank(userinfo)) {
            UserContext.setUser(Long.valueOf(userinfo));
        }
//        没有就不管
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        清理用户
        UserContext.removeUser();
    }
}
